package com.ny.zmb.openapi.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.ny.zmb.openapi.config.YsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import java.util.Map;

@Slf4j
public class YsPaySignUtils {

	/**
	 * 同步请求参数签名
	 */
	public static String sign(Map<String, String> mapData) throws Exception {
		//特别注意 商户在生产环境联调测试做签名，请替换成自己在CFCA申请的私钥证书
		//可以将密钥存入缓存获取内存中方便获取
		//1.3.1 商户私钥地址
		String path= new YsConfig().getMercPrivateFile();
//		String path="C:\\Users\\Lenovo\\Desktop\\Sm2\\826584848160007\\826584848160007_sm2.sm2";
		//1.3.2  将所有外层报文参数（sign除外）进行字典排序，组成字符串得到待签名内容
		String signContent = CommonUtil.mapToString(mapData);
		log.info("待签名内容：{}",signContent);
		//1.3.3 执行签名
//		String sign=GMSignUtils.signMsgSM2(path,"ys123456",signContent);
		String sign=GMSignUtils.signMsgSM2(path,"197Aa2569",signContent);
		//1.3.4 对sign进行url编码
		return sign;
	}
	/**
	 * 同步返回参数验签
	 *
	 * @throws Exception
	 */
	public static boolean resultVerify(String resTest, String repMethod) throws Exception {

		JSONObject jsonObject= JSON.parseObject(resTest, Feature.OrderedField);
		System.out.println("jsonObject:" + jsonObject);
		String content = jsonObject.get(repMethod).toString();
		String sign = jsonObject.get("sign").toString();
		System.out.println("sign:" + sign+"content:" + content);
		//请用银盛的公钥证书
		//公钥地址
		String path = new YsConfig().getYsPublicCerPath();
//		String path = "C:\\Users\\Lenovo\\Desktop\\Sm2\\sm2businessgate\\sm2businessgate.cer";
		//获取银盛公钥
		GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(path);
		//验签
		byte[] srcData = content.getBytes("UTF-8");
		boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(sign.getBytes("UTF-8")),srcData);
		return validateSignResult;
	}

	/**
	 * 异步通知参数验签
	 */
	public static boolean asynVerifyYs(Map<String, String> reqMap) throws Exception {
		//请用银盛的公钥证书
		//公钥地址
		String path = "/sm2/sm2businessgate.cer";
		//获取银盛公钥
		GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(path);
		//验签
		String sign = reqMap.get("sign");
		System.out.println("签名原文:"+reqMap);
		String content = StringUtil.createLinkString(CommonUtil.paraFilter(reqMap));
		System.out.println("验签数据"+content+","+sign);
		byte[] srcData = content.getBytes("UTF-8");
		boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo,Base64.decodeBase64(sign.getBytes("UTF-8")),srcData);

		return validateSignResult;
	}

	public static String encryptData(String data)  throws Exception{
		//请用银盛的公钥证书
		//公钥地址
		String path = "/sm2/sm2businessgate.cer";
//		String path = "C:\\Users\\Lenovo\\Desktop\\Sm2\\sm2businessgate\\sm2businessgate.cer";
		//加密
		return GMSignUtils.encryptData(path,data);
	}
}
